//
//  HouseCarLoanViewController.swift
//  KaMengApplication
//
//  Created by DUONIU_MAC on 2018/11/15.
//  Copyright © 2018年 DUONIU_MAC. All rights reserved.
//

import UIKit
import SwiftyJSON

class HouseCarLoanViewController: KMViewController {
    
    fileprivate let cellId = "houseCarLoanCell"
    fileprivate var dataArray = [GenericLoansModel]()
    
    fileprivate var page = 1
    fileprivate var loanType = "" //贷款类型
    fileprivate var bankName = "" //银行
    
    fileprivate var tableView : UITableView!
    fileprivate var headView : HouseCarLoanHeadView! //头部视图
    fileprivate let bankView = HouseCarLoanBankView() //更多银行

    
    init(title:String) {
        super.init(nibName: nil, bundle: nil)
        
        self.title = title
        
        if title == houseLoan {
            loanType = "house"
        }else{
            loanType = "car"
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        createTableView()
    }
    
    //MARK: 创建tableView
    fileprivate func createTableView() {
        
        headView = HouseCarLoanHeadView.init(frame: .init(x: 0, y: 0, width: ScreenW, height: RATIO_H(maxNum: 50)))
        headView.delegate = self
        headView.number = "0"
        headView.cityName = KMTool.stringForEnumKey(.currentCity) ?? ""
        headView.bankButton.addTarget(self, action: #selector(showMoreBank(sender:)), for: .touchUpInside)
        self.view.addSubview(headView)
        
        tableView = UITableView.init(frame: .zero, style: .plain)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(NewCityLoanCell.self, forCellReuseIdentifier: cellId)
        tableView.separatorStyle = .none
        self.view.addSubview(tableView)
        
        bankView.isHidden = true
        bankView.delegate = self
        self.view.addSubview(bankView)
        
        tableView.snp.makeConstraints { (make) in
            make.top.equalTo(headView.snp.bottom)
            make.left.right.bottom.equalToSuperview()
        }
        
        bankView.snp.makeConstraints { (make) in
            make.top.equalTo(headView.snp.bottom)
            make.left.right.bottom.equalToSuperview()
        }
        
        KMTool.setRefresh(with: tableView, headerAction: {[weak self] in
            
            self?.page = 1
            self?.getData()
            
        }) {[weak self] in
            
            self?.getData()
        }
        
        self.tableView.mj_header.beginRefreshing()
    }
    
    //MARK: 获取数据
    fileprivate func getData() {
        
        KMTool.requestGetData(URLString: url_houseCarLoan, parameters: ["psw":"kameng98_loan","type":self.loanType,"city":headView.cityName,"p":"\(self.page)","bank":self.bankName], success: { (data) in

            self.tableView.mj_header.endRefreshing()
            self.tableView.mj_footer.endRefreshing()

            let json = JSON.init(data)

            if let array = json.arrayObject {
                
                self.headView.number = "\(array.count)"

                if self.page == 1 {
                    self.dataArray.removeAll()
                }

//                if array.count > 0 {
//                    self.page += 1
//                }

                for item in array {
                    let model = GenericLoansModel.setModel(with: item as! [String : Any])
                    self.dataArray.append(model)
                }

                self.tableView.reloadData()
            }



        }) {

            self.tableView.mj_header.endRefreshing()
            self.tableView.mj_footer.endRefreshing()
        }
    }
    
    //MARK: 显示更多银行
    @objc fileprivate func showMoreBank(sender:ButtonView) {
        
        if sender.image == UIImage.init(named: "bottom_arrow") {
            sender.image = UIImage.init(named: "up_arrow")
            bankView.isHidden = false
        }else{
            sender.image = UIImage.init(named: "bottom_arrow")
            bankView.isHidden = true
        }
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        
    }

}

extension HouseCarLoanViewController : UITableViewDelegate,UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return dataArray.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        return RATIO_H(maxNum: 160)
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as? NewCityLoanCell
        cell?.model = dataArray[indexPath.row]
        return cell!
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        let model = dataArray[indexPath.row]
        
        let loanDetailsWebVC = LoanDetailsWebViewController.init(urlStr: model.id!,title:model.organization_name! + "-" + model.product_name!)
        loanDetailsWebVC.hidesBottomBarWhenPushed = true
        loanDetailsWebVC.removeElements = ["top-bar","footer"]
        self.navigationController?.pushViewController(loanDetailsWebVC, animated: true)
        
    }
}

extension HouseCarLoanViewController : HouseCarLoanBankViewDelegate,HouseCarLoanHeadViewDelegate {
    
    //MAKR: 选择银行
    func selectBankType(title: String) {
        
        headView.bankName = title
        headView.bankButton.image = UIImage.init(named: "bottom_arrow")
        bankView.isHidden = true
        
        if title == everyBanks {
            self.bankName = ""
        }else{
            self.bankName = title
        }
        
        self.page = 1
        self.getData()
    
    }
    
    //MARK: 选择城市
    func selectCityType() {
        
        headView.bankButton.image = UIImage.init(named: "bottom_arrow")
        bankView.isHidden = true
        
        let cityVC = CityViewController.init(currentCity: headView.cityName)
        cityVC.cityBlock = {(cityName) in
            
            self.headView.cityName = cityName
            self.page = 1
            self.getData()
        }
        cityVC.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(cityVC, animated: true)
    }
}
